import requests
import json
import schedule
import time
from bs4 import BeautifulSoup
import pymysql


#数据库配置
host = '127.0.0.1'
user = 'root'
password = 'root'
db = 'jmx2023'
charset = 'utf8'
port = 3306

def get_req(page):
    req_data={
        "name": "ssq",
        "issueCount": "",
        "issueStart":"", 
        "issueEnd":"", 
        "dayStart":"", 
        "dayEnd":"", 
        "pageNo": page,
        "pageSize": 30,
        "week": "",
        "systemType":"PC"
    }
    return req_data

# 连接数据库,返回连接
def get_conn():
    conn = pymysql.connect(host=host, port=port, user=user, password=password, db=db)
    return conn

#根据连接创建游标对象，返回游标对象
def get_cur(conn):
    cursor = conn.cursor()
    return cursor

# def operate_red(as_string):
#     # 使用逗号分隔字符串，将分隔后的子字符串存储在列表中  
#     numbers = as_string.split(",")  
#     # 输出分隔后的子字符串  
#     for number in numbers:  
#         print(number)


def insert(red01,red02,red03,red04,red05,red06,red_sum,blue,pub_time,number):
    try:
        conn=get_conn()
        cursor=get_cur(conn)
        # insert into welfare_lotto(pic_path,knowledge_id) VALUES("",(SELECT id FROM `baidu_wiki_knowledge` where key_name="半干法脱硫" and wiki_id=3))
        sql="insert into welfare_lotto(red01,red02,red03,red04,red05,red06,red_sum,blue,pub_time,number) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);"
        cursor.execute(sql,(red01,red02,red03,red04,red05,red06,red_sum,blue,pub_time,number))
        conn.commit()
    except Exception as e:
        print(str(e))
    finally:
        cursor.close()
        conn.close()


# rep=requests.get("https://www.cwl.gov.cn/ygkj/wqkjgg/ssq/")
# soup = BeautifulSoup(rep.content, 'html.parser')
# red=soup.select("body > div.main > div > div > div.ygkj_wqkjgg > div > div.body-content-item > div.table.ssq > table > tbody > tr:nth-child(1) > td:nth-child(3) > div > div:nth-child(1)")
# print(red)
        
pageNum=34
pageSize=40

while pageNum<=pageSize:
    rep=requests.get("https://www.cwl.gov.cn/cwl_admin/front/cwlkj/search/kjxx/findDrawNotice",params=get_req(pageNum))
    data=rep.json()['result']

    for res in data:
        pub_time=res['date']
        number=res['code']
        red_sum=res['red']
        blue=res['blue']

        # 使用逗号分隔字符串，将分隔后的子字符串存储在列表中  
        numbers = red_sum.split(",")  
        # 输出分隔后的子字符串  
        for i in range(len(numbers)):  
            if i==0:
                red01=numbers[i]
            if i==1:
                red02=numbers[i]
            if i==2:
                red03=numbers[i]
            if i==3:
                red04=numbers[i]
            if i==4:
                red05=numbers[i]
            if i==5:
                red06=numbers[i]

        insert(red01,red02,red03,red04,red05,red06,red_sum,blue,pub_time,number)

    pageNum=pageNum+1
    time.sleep(3)




